<template>
  <view>
    <u-navbar title="搜索" :is-back="true" :background="background" titleColor="#fff">
      <!-- 添加返回按钮 -->
      <u-icon slot="left" name="arrow-left" color="#ffffff" @click="goBack"></u-icon>
    </u-navbar>
    <view class="search-container">
      <u-input v-model="keyword" placeholder="请输入关键词搜索" />
      <u-button type="primary" @click="search">搜索</u-button>
    </view>
    <view class="results">
      <view class="result-item" v-for="(item, index) in list" :key="index" @click="toDetail(item.id)">
        <u-image width="100" height="100" :src="item.cover_img || '/static/default-image.jpg'" borderRadius="12"></u-image>
        <view class="item-info">
          <view class="item-name">{{ item.name || '无名称' }}</view> <!-- 确保这里使用的是正确的字段名 -->
          <view class="item-price">￥{{ item.price }}</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      background: {
        'background-image': 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
      },
      keyword: '',
      list: [], // 存储搜索结果的数组
    };
  },
  methods: {
    goBack() {
      // 返回分类页面
      uni.switchTab({
        url: '/pages/category/index'
      });
    },
    search() {
      // 使用uni.request调用后端API接口，获取搜索结果
      uni.request({
        url: 'http://localhost:8084/good/search', // 确保这里是正确的 API 路径
        method: 'GET',
        data: {
          name: this.keyword // 使用 name 作为查询参数
        },
        success: (res) => {
          if (res.statusCode === 200 && res.data.status === 1) {
            this.list = res.data.data; // 将搜索结果存储在list中
          } else {
            console.error(res.data.message);
            uni.showToast({
              icon: "none",
              title: res.data.message || '未找到相关商品'
            });
          }
        },
        fail: (err) => {
          console.error(err);
          uni.showToast({
            icon: "none",
            title: '搜索失败，请重试'
          });
        }
      });
    },
    toDetail(id) {
      // 跳转到商品详情页
      uni.navigateTo({
        url: `/pages/index/detail?good_id=${id}`
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
}

.results {
  margin-top: 20rpx;
}

.result-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  cursor: pointer;
}

.item-info {
  flex: 1;
  padding: 0 20rpx;
}

.item-name {
  font-size: 28rpx;
  margin-top: 10rpx;
  color: #333;
}

.item-price {
  font-size: 24rpx;
  margin-top: 4rpx;
  color: #ff5722;
}
</style>